package com.mengdie.shuidi.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.mengdie.shuidi.AppContext;
import com.mengdie.shuidi.OkHeader;
import com.mengdie.shuidi.manager.MDAccountMgr;
import com.orhanobut.logger.Logger;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Response;

/**
 * 作者：HQY on 16/11/4 16:05
 * 邮箱：hqy_xz@126.com
 */

public class BeatService extends Service {
    protected Timer mHearBeatTimer;
    protected HeartBeatTask mHeartBeatTask;//心跳

    @Override
    public void onCreate() {
        super.onCreate();
        mHearBeatTimer = new Timer(true);
        mHeartBeatTask = new HeartBeatTask();
        mHearBeatTimer.schedule(mHeartBeatTask, 1000, 600 * 1000);
    }

    /**
     * 直播心跳
     */
    protected class HeartBeatTask extends TimerTask {
        @Override
        public void run() {
            OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(BeatService.this)).
                    post(AppContext.getInstance().getBaseUrl()+"client/c_heartbeat")
                    .tag(this)
                    .upJson(mapSession())
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {

                        }
                    });
        }
    }

    public String mapSession() {
        HashMap<String, String> map = new HashMap<>();
        map.put("session_id", MDAccountMgr.getInstance().getSessionId());
        JSONObject json = new JSONObject(map);
        return json.toString();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != mHearBeatTimer) {
            Logger.e("关闭服务1");
            mHearBeatTimer.cancel();
            mHearBeatTimer = null;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
